<!--
 * @Descripttion: 考试计划列表操作页面
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-05-18 11:19:06
 * @LastEditTime: 2021-07-07 15:23:52
 * @FilePath: \cscec-pms-admin\src\views\partyMasses\partyManage\examinationPlan\update.vue
-->
<template>
  <base-breadcrumb
    class="UpdateStudyEduc-container"
    :title="breadcrumbTitle"
  >
    <a-spin :spinning="!!loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="基础信息" />
        <custom-form
          ref="ruleForm"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="form"
          :form-list="formOption"
          @change="handleChange"
        />
        <title-name title="参考人员信息" />
        <party-member-table
          ref="memberTable"
          :mode="pageType"
          :btn-text="'新增参考人员'"
          :request-fn="queryPlanMemberList"
          :request-args="{ query: { examPlanId: $route.query.id } }"
          convert-key="userId"
          @confirm="handleConfirm"
          @reload="handleConfirm"
        />
      </a-card>
      <div class="tool-btns page-btn-right-top">
        <a-button
          v-if="!isDisabled"
          class="ml12"
          type="primary"
          :loading="loadingState.DRAFT"
          @click="handleSubmit('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="!isDisabled"
          :disabled="!people.length>0"
          class="ml12"
          type="primary"
          :loading="loadingState.SUBMITTED"
          @click="handleSubmit('SUBMITTED')"
        >
          发送
        </a-button>
        <a-button
          class="ml12"
          type="default"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
    </a-spin>
  </base-breadcrumb>
</template>
<script>
import Vue from 'vue'
import Moment from 'moment'
import PartyMemberTable from '../../componments/PartyMemberTable.vue'
import {
  queryExamPaperList,
  queryPlanMemberList,
  insertOrUpdateSelective,
  sendExamPlan,
  getExamPlanById
} from '@/api/partyMasses/partyManage/examinationPlan'
import { packageConfirm } from '@/utils/baseAction.js'
export default {
  name:'a'+ Date.now(),
  // name: 'Update',
  components: {
    PartyMemberTable
  },
  data() {
    return {
      // 表单
      form: {
        people: 0
      },
      // 参考人员列表
      people: [],
      // 页面加载
      loadingState: {
        isDetail: true,
        DRAFT: false,
        SUBMITTED: false
      },
      // 依赖数据
      depend: {
        examPaperId: []
      },
      // 新增参考人员接口
      queryPlanMemberList
    }
  },
  computed: {
    // 页面类型
    pageType() {
      return this.$route.query.pageType || 'look'
    },
    // 标题
    breadcrumbTitle() {
      const obj = {
        add: '新增考试计划',
        edit: '编辑考试计划',
        look: '查看考试计划'
      }
      return obj[this.pageType] || obj.look
    },
    // 查看禁用
    isDisabled() {
      return this.pageType === 'look'
    },
    // 表单配置
    formOption() {
      return [
        {
          label: '考试计划名称',
          keyName: 'name',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '考卷名称',
          keyName: 'examPaperId',
          type: 'a-select',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          data: this.depend.examPaperId
        },
        {
          label: '考卷总分',
          keyName: 'totalScore',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '计划开始时间',
          keyName: 'startTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            disabledDate: this.disabledStartDate,
            showTime: { format: 'YYYY-MM-DD HH:mm:ss' }
          }
        },
        {
          label: '计划结束时间',
          keyName: 'endTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            disabledDate: this.disabledEndDate,
            showTime: { format: 'YYYY-MM-DD HH:mm:ss' }
          }
        },
        {
          label: '创建人',
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '考试人数',
          keyName: 'people',
          type: 'BaseInput',
          disabled: true
        }
      ]
    },
    // 校验
    rules() {
      const obj = {}
      this.formOption.map((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    }
  },
  async created() {
    this.initPage()
    await this.getSearchData()
    this.getDetail()
  },
  methods: {
    /**
     * @description: 页面初始化获取信息
     * @param {Void}
     * @return {Void}
     */
    initPage() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      this.form = {
        ...this.form,
        creatorName: userInfo.name,
        createTime: curDate
      }
    },
    /**
     * @description: 获取依赖数据
     * @param {Void}
     * @return {Promise} 接口Promise
     */
    getSearchData() {
      return new Promise((resolve, reject) => {
        queryExamPaperList({
          examPaperName: '',
          examPaperState: 1
        })
          .then(({ data }) => {
            this.depend.examPaperId = data.map((el) => {
              return {
                label: el.name,
                value: el.id,
                totalScore: el.totalScore
              }
            })
            resolve()
          })
          .catch((error) => {
            console.log(error)
            reject(error)
          })
      })
    },
    /**
     * @description: 获取基础信息
     * @param {Void}
     * @return {Void}
     */
    async getDetail() {
      try {
        this.loadingState.isDetail = true
        if (this.$route.query.id) {
          await getExamPlanById({ id: this.$route.query.id })
            .then(({ data }) => {
              this.form = {
                ...this.form,
                name: data.name,
                examPaperId: data.examPaperId,
                startTime: data.startTime,
                endTime: data.endTime,
                creatorName: data.creatorName,
                createTime: data.createTime,
                totalScore: this.depend.examPaperId.find((el) => el.value === data.examPaperId)?.totalScore
              }
              this.loadingState.isDetail = false
            })
            .catch((error) => {
              console.log(error)
              this.loadingState.isDetail = false
            })
        } else {
          this.loadingState.isDetail = false
        }
      } catch (error) {
        console.error(error)
        this.loadingState.isDetail = false
      }
    },
    /**
     * @description: 计划开始时间约束
     * @param {String} startValue 计划开始时间
     * @return {Boolean} 是否禁止选择
     */
    disabledStartDate(startValue) {
      const endValue = this.form.endTime ? Moment(this.form.endTime) : null
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
      // if (!endValue) {
      //   return false && startValue.valueOf() < Moment()
      // }
      // return startValue.valueOf() > endValue.valueOf() && startValue.valueOf() < Moment()
    },
    /**
     * @description:  计划结束时间约束
     * @param {String} endValue 计划结束时间
     * @return {Boolean} 是否禁止选择
     */
    disabledEndDate(endValue) {
      const startValue = this.form.startTime ? Moment(this.form.startTime) : null
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    /**
     * @description: 表单改变
     * @param {String} key 表单项
     * @param {Any} data 表单数据
     * @return {Void}
     */
    handleChange(key, data) {
      // 设置考卷总分
      if (key === 'examPaperId') {
        this.form.totalScore = this.depend.examPaperId.find((el) => el.value === data).totalScore
      }
    },
    /**
     * @description: 保存草稿、发送
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     * @return {Promise} 接口返回
     */
    async handleSubmit(actionName) {
      const { name, examPaperId, startTime, endTime } = this.form
      const id = this.pageType === 'add' ? void 0 : this.$route.query.id
      let start = void 0
      let end = void 0
      if (typeof startTime === 'object') {
        if (startTime !== null) {
          start = Moment(startTime).format('YYYY-MM-DD HH:mm:ss')
        }
      } else {
        start = startTime
      }
      if (typeof endTime === 'object') {
        if (endTime !== null) {
          end = Moment(endTime).format('YYYY-MM-DD HH:mm:ss')
        }
      } else {
        end = endTime
      }
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          packageConfirm({
            content: '请确认是否发送？'
          }).then(async (res) => {
            if (res !== 'cancel') {
              this.loadingState[actionName] = true
              sendExamPlan({
                id,
                name,
                examPaperId,
                startTime: start,
                endTime: end,
                memberUserIds: this.people.map((el) => el.userId)
              })
                .then(({ code, msg }) => {
                  this.loadingState[actionName] = false
                  if (code === this.SUCCESS_CODE) {
                    this.$message.success('发送成功')
                    this.handleClose()
                  } else {
                    this.$message.error(msg)
                  }
                })
                .catch((error) => {
                  console.log(error)
                  this.loadingState[actionName] = false
                  this.$message.error('发送失败')
                })
            }
          })
        })
      } else {
        this.loadingState[actionName] = true
        insertOrUpdateSelective({
          id,
          name,
          examPaperId,
          startTime: start,
          endTime: end,
          memberUserIds: this.people.map((el) => el.userId)
        })
          .then(({ code }) => {
            this.loadingState[actionName] = false
            if (code === this.SUCCESS_CODE) {
              this.$message.success('保存成功')
              this.handleClose()
              return Promise.resolve()
            } else {
              this.$message.error('保存失败')
              return Promise.reject()
            }
          })
          .catch((error) => {
            console.log(error)
            this.loadingState[actionName] = false
            this.$message.error('保存失败')
            return Promise.reject()
          })
      }
    },
    /**
     * @description: 关闭
     * @param {Void}
     * @return {Void}
     */
    handleClose() {
      this.$close()
    },
    /**
     * @description: 人员选择回调
     * @param {Void}
     * @return {Void}
     */
    handleConfirm() {
      this.people = this.$refs.memberTable.getChangedData().allList
      this.form.people = this.people.length
    }
  }
}
</script>
<style lang="less" scoped>
</style>
